package cn.vconinfo.database.aspect;

import cn.vconinfo.database.annotation.TargetDataSource;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

/**
 * 切换数据源
 * @author vconinfo
 * @createdOn 2018/4/30
 * @description:
 */
@Aspect
@Order(-10)// 保证该AOP在@Transactional之前执行
@Component
public class DynamicDataSourceAspect {
    protected static final Logger log = LoggerFactory.getLogger(DynamicDataSourceAspect.class);

    @Before("@annotation(targetDataSource)")
    public void changeDataSource(JoinPoint point, TargetDataSource targetDataSource)  throws Throwable {
        String dsId = targetDataSource.value();
        if (!DynamicDataSourceContextHolder.containsDataSource(dsId)) {
            log.error("数据源[{}]不存在，使用默认数据源 > {}", targetDataSource.value(), point.getSignature());
        } else {
            log.debug("Use DataSource : {} > {}", targetDataSource.value(), point.getSignature());
            DynamicDataSourceContextHolder.setDataSourceType(targetDataSource.value());
        }
    }

    @After("@annotation(targetDataSource)")
    public void restoreDataSource (JoinPoint point, TargetDataSource targetDataSource) throws Throwable {
        log.debug("Revert DataSource : {} > {}", targetDataSource.value(), point.getSignature());
        DynamicDataSourceContextHolder.clearDataSourceType();
    }
}
